﻿# -*- coding:utf-8 -*-
#
# склад
#
import os.path
import re
import ktit


def recursive_get_category_list(category, level):
    res = []
    for cat in category:
        item = {"id":cat.id,"name":cat.name,"parent":cat.parent,"level":level,"csslevel":level*24,}
        category_set = cat.category_set.all()
        item["child_present"] = category_set
        res.append(item)
        subcategory=recursive_get_category_list(category_set, level+1)
        res.extend(subcategory)
    return res



def create_category_tree():
    d = Category.objects.select_related().filter(parent=None)
    category = recursive_get_category_list(d, 0)
    level_prev = 0
    for cat in category:
        level_div = level_prev - cat["level"]
        if level_div < 0:
            cat["level_div"] = range(0) 
        else:
            cat["level_div"] = range(level_div)      
        level_prev = cat["level"]
    return category



def get_svn_revision_ex(path=None):
    """
    Returns the SVN revision in the form XXXX,
    where XXXX is the revision number.

    Returns 'unknown' if anything goes wrong, such as an unexpected
    format of internal SVN files.

    If path is provided, it should be a directory whose SVN info you want to
    inspect. If it's not provided, this will use the root ktit/ package
    directory.
    """
    rev = None
    if path is None:
        path = ktit.__path__[0]
    entries_path = '%s/.svn/entries' % path

    try:
        entries = open(entries_path, 'r').read()
    except IOError:
        pass
    else:
        # Versions >= 7 of the entries file are flat text.  The first line is
        # the version number. The next set of digits after 'dir' is the revision.
        if re.match('(\d+)', entries):
            rev_match = re.search('\d+\s+dir\s+(\d+)', entries)
            if rev_match:
                rev = rev_match.groups()[0]
        # Older XML versions of the file specify revision as an attribute of
        # the first entries node.
        else:
            from xml.dom import minidom
            dom = minidom.parse(entries_path)
            rev = dom.getElementsByTagName('entry')[0].getAttribute('revision')
    if rev:
        return u'%s' % rev
    return u'unknown'
